<template>
  <view class="video-container">
    <mTikTok
      ref="mTikTokRef"
      @loadMore="loadMore"
      @change="change"
      :loadMoreOffsetCount="1"
      :autoplay="true"
      :circular="true"
    >
      <template v-slot="data">
        <view class="video-side-right">
          <!-- <view class="action-item action-item-user">
            <image
              class="shop-logo"
              src="https://examples-1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?imageMogr2/crop/180x180/gravity/center"
            />
            <view class="action-btn">
              <text class="iconfont">+</text>
            </view>
            <text class="action-item-text"></text>
          </view> -->
          <!-- 点赞 -->
          <view class="action-item" @click="setLike()">
            <image
              class="acion-item-icon"
              v-show="data.item.is_like == 0"
              src="@/static/icon/svg/video/love.svg"
            ></image>
            <image
              class="acion-item-icon"
              v-show="data.item.is_like == 1"
              src="@/static/icon/svg/video/love_active.svg"
            ></image>
            <text class="action-item-text">{{ data.item.like_num }}</text>
          </view>

          <!-- 评论 -->
          <view class="action-item" @click="openComment()">
            <image class="acion-item-icon" src="@/static/icon/svg/video/msg.svg"></image>
            <text class="action-item-text">{{ data.item.comment_num }}</text>
          </view>

          <!-- 分享 -->
          <button class="action-item share-btn" open-type="share" hover-class="none">
            <image class="acion-item-icon share-icon" src="@/static/icon/svg/video/share.svg" />
            <text class="share-text">分享</text>
          </button>
        </view>
        <view class="video-bottom-area">
          <view class="author-name" v-if="data.item.author"> @{{ data.item.author }} </view>
          <view class="desc">{{ data.item.description }}</view>
        </view>
      </template>
    </mTikTok>

    <mt-drawer v-model:show="showWin" height="70">
      <view class="drawer-box">
        <text class="comment-title">评论 ( {{ comments.total }} )</text>

        <view class="h-full">
          <view class="comment-box">
            <z-paging
              ref="paging"
              class="comment-list"
              v-model="comments.list"
              :default-page-size="comments.limit"
              :fixed="false"
              :auto="false"
              :min-delay="800"
              :show-loading-more-no-more-view="false"
              :auto-hide-loading-after-first-loaded="true"
              :refresher-enabled="false"
              @query="queryCommentData"
            >
              <view class="comment-item" v-for="(comment, index) in comments.list" :key="index">
                <view class="comment-left">
                  <image
                    class="user-avatar"
                    :src="comment.fansinfo.avatar || config.custom.avatar"
                    @error="comment.fansinfo.avatar = config.custom.avatar"
                  />
                </view>
                <view class="comment-right">
                  <text class="user-name">{{ comment.fansinfo.nickname }}</text>
                  <text class="comment-content">{{ comment.content }}</text>
                  <text class="comment-date">{{ getDayAgo(comment.created_at) }}</text>
                </view>
              </view>

              <template #empty>
                <view class="no-data-box">
                  <text>暂无评论</text>
                  <image class="no-data-img" src="@/static/image/video/chats.svg"></image>
                </view>
              </template>

              <template #loading>
                <view class="loading">
                  <mt-logo-loading :size="88"></mt-logo-loading>
                </view>
              </template>
            </z-paging>
          </view>
        </view>

        <view class="dialog-box">
          <view class="dialog-text">
            <textarea
              class="dialog-textarea"
              type="textarea"
              placeholder="请友善发言"
              v-model="comment"
              :show-confirm-bar="false"
              :auto-height="true"
              :adjust-position="false"
              @focus="dialogFocus"
              @blur="dialogBlur"
            />
            <text class="send-btn" @click="sendComment()">发送</text>
          </view>
          <view class="keybord"></view>
        </view>
      </view>
    </mt-drawer>
  </view>
</template>
<script lang="ts" setup>
  import mTikTok from '@/components/mt-video/mt-video.vue';
  import mtDrawer from '@/components/mt-drawer/mt-drawer.vue';
  import mtLogoLoading from '@/components/mt-loading/mt-logo-loading.vue';
  import { nextTick, reactive, ref } from 'vue';
  import { getVideos, getVideoDetails, setVideoLike, setVideoComment, getVideoComments } from '@/api/video';
  import { report } from '@/utils/exception';
  import { getDayAgo, getNow } from '@/utils/day';
  import { msg } from '@/utils/msg';
  import { useFansStore } from '@/store/fans';
  import { onLoad, onShareAppMessage, onUnload } from '@dcloudio/uni-app';
  import { config } from '@/config/env';
  import type { VideoItem, VideoCommentItem } from '@/types/video';

  const fansStore = useFansStore();
  const mTikTokRef = ref<InstanceType<typeof mTikTok>>();
  const state = reactive({
    page: 0,
    total: 0,
    limit: 3,
    currentIdx: 0,
    videoId: 0,
    maxVideoId: 0,
    videoList: <VideoItem[]>[],
  });
  let isChangeLike = false;

  // 触发加载更多
  const loadMore = () => {
    if (state.total <= state.videoList.length) {
      return false;
    }

    state.page++;

    getVideos(state.page, state.limit, 0)
      .then((res) => {
        setTimeout(() => {
          state.total = res.data.pages.total;
          res.data.list.forEach((item: VideoItem) => {
            state.videoList.push(item);
          });
        }, 800);
      })
      .catch((err) => {
        report(err);
      });
  };

  const change = (e: any) => {
    comment.value = '';
    state.currentIdx = e.index;
    state.videoId = state.videoList[state.currentIdx].id;
  };

  onLoad((option: any) => {
    state.videoId = option.id;

    getVideoDetails(option.id, state.limit)
      .then((res) => {
        state.videoList = res.data.list;
        state.total = res.data.pages.total;
        state.page = res.data.pages.page;
        state.currentIdx = res.data.index;
        nextTick(() => {
          mTikTokRef.value?.setup(state.videoList, state.currentIdx);
        });
      })
      .catch((err) => {
        report(err);
      });
  });

  onUnload(() => {
    if (!isChangeLike) return false;
    uni.$emit('syncVideoLike');
  });

  // 点赞
  let timer: any;
  const setLike = () => {
    state.videoList[state.currentIdx].is_like = state.videoList[state.currentIdx].is_like == 0 ? 1 : 0;
    state.videoList[state.currentIdx].is_like == 1
      ? state.videoList[state.currentIdx].like_num++
      : state.videoList[state.currentIdx].like_num > 0
        ? state.videoList[state.currentIdx].like_num--
        : 0;

    clearTimeout(timer);
    timer = setTimeout(() => {
      setVideoLike(state.videoId, state.videoList[state.currentIdx].is_like)
        .then((res) => {
          isChangeLike = true;
        })
        .catch((err) => {
          report(err);
          state.videoList[state.currentIdx].is_like = state.videoList[state.currentIdx].is_like == 0 ? 1 : 0;
          state.videoList[state.currentIdx].is_like == 1
            ? state.videoList[state.currentIdx].like_num++
            : state.videoList[state.currentIdx].like_num > 0
              ? state.videoList[state.currentIdx].like_num--
              : 0;
        });
    }, 500);
  };

  const paging = ref();
  const showWin = ref<boolean>(false);
  const comment = ref<string>('');
  const comments = reactive({
    list: <VideoCommentItem[]>[],
    limit: 6,
    total: 0,
  });

  const dialogBottom = ref<string>('0');
  const dialogFocus = (event: any) => {
    dialogBottom.value = event.detail.height > 0 ? event.detail.height + 'px' : '301px';
  };
  const dialogBlur = () => {
    dialogBottom.value = '0';
  };

  // 请求评论数据
  const queryCommentData = (pageNo: number, pageSize: number) => {
    getVideoComments(pageNo, pageSize, state.videoId)
      .then((res) => {
        comments.total = res.data.pages.total;
        state.videoList[state.currentIdx].comment_num = comments.total;
        paging.value.complete(res.data.list);
      })
      .catch((err) => {
        report(err);
        paging.value.complete(false);
      });
  };

  // 打开评论
  let commentIdx = -1;
  const openComment = () => {
    showWin.value = true;

    if (commentIdx != state.currentIdx) {
      commentIdx = state.currentIdx;
      comments.total = 0;
      paging.value.reload();
    }
  };

  // 评论
  let commentTmp = '';
  const sendComment = () => {
    if (!comment.value) {
      return msg.error('请填写评论');
    }

    if (comment.value == commentTmp) {
      return msg.error('请勿重复评论');
    }

    msg.loading('发送中');
    setVideoComment(state.videoId, comment.value)
      .then((res) => {
        paging.value.addDataFromTop({
          fansinfo: { nickname: fansStore.fansinfo.nickname, avatar: fansStore.fansinfo.avatar },
          content: comment.value,
          created_at: getNow(),
        });
        commentTmp = comment.value;
        comment.value = '';
        comments.total++;
        state.videoList[state.currentIdx].comment_num = comments.total;
        setTimeout(() => {
          msg.success('评论发送成功！');
        }, 500);
      })
      .catch((err) => {
        report(err);
      });
  };

  /* #ifdef MP-WEIXIN */
  // 分享
  onShareAppMessage((res) => {
    return {
      title: state.videoList[state.currentIdx].description,
      path: '/pages/video/detail?id=' + state.videoId,
      // imageUrl: '',
    };
  });

  uni.showShareMenu({
    menus: ['shareAppMessage', 'shareTimeline'],
    withShareTicket: true,
  });
  /* #endif */
</script>

<style lang="scss" scoped>
  .video-layer {
    position: absolute;
    right: 12px;
    bottom: 120px;
    color: #fff;
  }

  .video-side-right {
    position: absolute;
    right: 15rpx;
    bottom: 240rpx;
    color: #fff;
    z-index: 999;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      margin-bottom: 40rpx;
      .shop-logo {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        overflow: hidden;
      }
      .action-btn {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: -8px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f60;
        .iconfont {
          font-size: 16px;
        }
      }
      .acion-item-icon {
        width: 60rpx;
        height: 60rpx;
        opacity: 0.9;
      }
      .action-item-text {
        margin-top: 3rpx;
        font-size: 26rpx;
      }
      .share-icon {
        width: 65rpx;
        height: 65rpx;
      }
      .share-text {
        font-size: 22rpx;
        position: relative;
        top: -20rpx;
      }
    }

    .share-btn {
      display: flex;
      flex-direction: column;
      top: -10rpx;
      color: white;
    }
    .action-item-user {
      margin-bottom: 40px;
    }
  }

  button {
    background: transparent;
    &::after {
      border: none;
    }
  }

  .video-bottom-area {
    position: absolute;
    left: 40rpx;
    bottom: 120rpx;
    z-index: 999;
    .author-name {
      color: #fff;
      margin-bottom: 20rpx;
      font-size: 34rpx;
    }
    .desc {
      width: 600rpx;
      height: 72rpx;
      line-height: 40rpx;
      color: #fff;
      font-size: 30rpx;
      display: -webkit-box;
      overflow: hidden;
      text-overflow: ellipsis;
      text-overflow: -o-ellipsis-lastline;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }

  .drawer-box {
    padding-bottom: 216rpx;
    height: 100%;

    .comment-title {
      display: flex;
      justify-content: center;
      font-size: 32rpx;
      font-weight: bold;
      padding: 25rpx 0;
    }

    .comment-box {
      height: 100%;

      .no-data-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 700rpx;

        .no-data-img {
          width: 380rpx;
        }
      }

      .comment-list {
        height: 100%;

        .comment-item {
          display: flex;
          padding-top: 30rpx;
          padding-left: 40rpx;

          .comment-left {
            padding-right: 20rpx;

            .user-avatar {
              width: 80rpx;
              height: 80rpx;
              border-radius: 50%;
            }
          }

          .comment-right {
            display: flex;
            flex-direction: column;
            padding-right: 40rpx;
            padding-bottom: 30rpx;
            flex: 1;

            .user-name {
              font-size: 26rpx;
              color: #7e7e7e;
            }

            .comment-content {
              font-size: 29rpx;
              line-height: 40rpx;
              font-weight: 600;
              padding: 10rpx 0;
              letter-spacing: 2rpx;
            }

            .comment-date {
              font-size: 24rpx;
              color: #b5b5b5;
            }
          }

          &:not(:last-child) .comment-right {
            border-bottom: 1px solid #ececec;
          }
        }
      }
    }

    .loading {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 500rpx;
    }

    .dialog-box {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      background: white;
      box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 12px;
      padding: 25rpx 20rpx 25rpx 35rpx;
      z-index: 10;
      // transition: all .2s ease;

      .dialog-text {
        display: flex;
        align-items: flex-end;
      }

      .dialog-textarea {
        width: 550rpx;
        max-height: 240rpx;
        font-size: 30rpx;
        overflow-y: auto;
        padding: 18rpx 20rpx;
        border-radius: 12rpx;
        background: #f2f2f2;
      }

      .keybord {
        height: v-bind(dialogBottom);
      }

      .send-btn {
        display: flex;
        flex: none;
        font-size: 30rpx;
        background: $themeColor;
        color: white;
        padding: 19rpx 28rpx;
        margin-left: 20rpx;
        border-radius: 12rpx;
      }
    }
  }
</style>
